package com.zhangh.summer.admin.support.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

/**
 * @description: TODO
 * @author: zhanghui  zhanghlucky@163.com
 * @create: 2021-06-10 22:12
 **/

@Slf4j
public class MD5Util {

    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    /**
     * byte to hex
     * @param b byte
     * @return  hex string
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte value : b) {
            resultSb.append(byteToHexString(value));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * md5值
     * @param origin 入参
     * @return md5
     */
    public static String MD5(String origin) {
        String resultString = null;
        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString
                    .getBytes()));
        } catch (Exception e) {
            log.error("md5 error:{}",e.getMessage());
            e.printStackTrace();
        }
        return resultString;
    }
}

